import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { FormDef } from '../fb-design.model';
import { FormDesignService } from '../fb-design.service';
import { SelectItem, DynamicDialogConfig, DynamicDialogRef } from 'primeng/primeng';

@Component({
    templateUrl: './fb-add.component.html',
    styleUrls: ['./fb-add.component.scss'],
    providers: [FormDesignService]
})
export class FormAddComponent implements OnInit {

    addForm: FormGroup;
    bizs: SelectItem[] = [];
    bizProcs: SelectItem[] = [];
    procs: SelectItem[] = [];
    biz: SelectItem;
    proc: SelectItem;
    formDef: FormDef = new FormDef({});

    constructor(
        private fb: FormBuilder,
        private ref: DynamicDialogRef, 
        private config: DynamicDialogConfig,
        private FormDesignService: FormDesignService) {
    }

    ngOnInit() {
        /**初始化业务类型流程选项 */
        this.FormDesignService.listBizProcs().subscribe(data => {
            let addedBiz = [];
            data.forEach(element => {
                if ($.inArray(element['bizId'], addedBiz) == -1) {
                    this.bizs.push({ label: element['bizName'], value: element['bizId'] });
                    addedBiz.push(element['bizId'])
                }
                this.procs.push({ label: element['procDefName'], value: element['procDefId'], title: element['bizId'] });
            });
        });
        this.buildForm();
    }
    /**新增表单 */
    save() {
        let formDef = this.addForm.value;
        if(this.biz && this.proc){
            formDef.bizName = this.biz.label;
            formDef.procDefName = this.proc.label;
        }else{
            //自定义，id设置为负值
        }
        this.FormDesignService.saveUpdateFormDef(formDef).subscribe(data => {
            this.ref.close(data['formId']);
        });
    }
    
    /**取消关闭窗口 */
    cancel() {
        this.ref.close();
    }

    /**表单名称搜索过滤 */
    filterForm($event){
    }

    buildForm(): void {
        this.addForm = this.fb.group({
            'formName': [this.formDef.formName, [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
            'bizId': [this.formDef.bizId],
            'procDefId': [this.formDef.procDefId]
        });
        this.addForm.valueChanges
            .subscribe(data => this.onValueChanged(data));
        this.onValueChanged();
    }

    onValueChanged(data?: any) {
        if (!this.addForm) { return; }
        const form = this.addForm;
        for (const field in this.formErrors) {
            this.formErrors[field] = '';
            const control = form.get(field);
            if (control && control.dirty && !control.valid) {
                const messages = this.validationMessages[field];
                for (const key in control.errors) {
                    this.formErrors[field] += messages[key] + ' ';
                }
            }
        }
    }

    formErrors = {
        'formName': ''
    };

    validationMessages = {
        'formName': {
            'required': '表单名称为必填项',
            'minlength': '数据源名称长度必须大于2',
            'maxlength': '数据源名称长度必须小于20'
        }
    };

     /**业务类型变更 */
     bizChange($event: any) {
        this.bizs.forEach(data => {
            if (data.value == $event.value) {
                this.biz = data;
                this.bizProcs = [];
                this.procs.forEach(ele => {
                    if (ele.title == this.biz.value + "") {
                        this.bizProcs.push(ele);
                    }
                });
            }
        })
    }
    /** 流程类型变更 */
    procChange($event : any){
        this.bizProcs.forEach(data => {
            if (data.value == $event.value) {
                this.proc = data;
            }
        });
    }

}
